package cn.alusiaor.eurekaclientuserservice;

import cn.alusiaor.commonutil.ServerPortUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.util.StringUtils;

@ServletComponentScan
@SpringBootApplication
@EnableDiscoveryClient
@Slf4j
public class EurekaClientUserServiceApplication {

    public static void main(String[] args) {
        new StartCommand(args);
        SpringApplication.run(EurekaClientUserServiceApplication.class, args);
    }

    static class StartCommand {
        public StartCommand(String[] args) {
            Boolean isServerPort = false;
            String serverPort = "";
            if (args != null) {
                for (String arg : args) {
                    if (StringUtils.hasText(arg) && arg.startsWith("--server.port")) {
                        isServerPort = true;
                        serverPort = arg;
                        break;
                    }
                }
            }
            // 没有指定端口，则随机生成一个可用的端口
            if (!isServerPort) {
                int port = ServerPortUtil.getAvailablePort();
                log.info("current server.port=" + port);
                System.setProperty("server.port", String.valueOf(port));
            } else {
                log.info("current server.port=" + serverPort.split("=")[1]);
                System.setProperty("server.port", serverPort.split("=")[1]);
            }
        }
    }
}
